import os
import random

from django.contrib.auth import get_user_model
from django.shortcuts import redirect
from django.utils.timezone import now
from rest_framework import views, status, permissions
from rest_framework.decorators import action
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response

from apps.flyauth.authentications import generate_jwt, JWTAuthentication
from apps.flyauth.serializers import UserSerializer
from apps.h5.serializers import LoginSerializer
from django.core.cache import cache
from rest_framework import viewsets, mixins, generics, filters

from apps.meituan.models import Merchant, GoodsCategory, UserAddress, Goods
from apps.meituan.serializers import MerchantSerializer, GoodsCategorySerializer, AddressSerializer
from mt_vue_django import settings
# from alipay import AliPay

User = get_user_model()


class SmsCodeView(views.APIView):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.numbers = ['0', '1', '2', '3', '4'
                                            '5', '6', '7', '8', '9']

    def get(self, request):
        # /smscode?tel=100XX
        telephone = request.GET.get("tel")
        code = self.generate_sms_code()
        while len(code) != 4:
            code = self.generate_sms_code()

        cache.set(telephone, code, 60 * 60 * 5)

        datas = ('123', code)
        # rest = send_message(telephone, datas)
        return Response({'code': code})

    def generate_sms_code(self):
        return ''.join(random.choices(self.numbers, k=4))


class LoginView(views.APIView):
    def post(self, request):

        serializer = LoginSerializer(data=request.data)
        if not serializer.is_valid():
            return Response("err")

        if serializer.is_valid():
            telephone = serializer.validated_data.get('telephone')
            try:
                print("login User: ")
                user = User.objects.get(telephone=telephone)
                user.last_login = now()
                user.save()
            except:
                print("create User: ")
                username = "FlyUser" + str(random.randint(1, 9999999999))
                password = "123456"
                user = User.objects.create(username=username, password=password, telephone=telephone)
                user.create_time = now()
                user.save()
            serializer = UserSerializer(user)
            token = generate_jwt(user)
            print(serializer)
            return Response({'user': serializer.data, 'token': token}, status=status.HTTP_200_OK)
        else:
            return Response("err")


class MerchantPagination(PageNumberPagination):
    page_size = 8
    page_query_param = 'page'


class MerchantViewSet(
    viewsets.GenericViewSet,
    mixins.ListModelMixin,
    mixins.RetrieveModelMixin,
):
    authentication_classes = [JWTAuthentication]
    queryset = Merchant.objects.order_by('-create_time').all()
    serializer_class = MerchantSerializer
    permission_classes = [permissions.IsAuthenticated, permissions.IsAdminUser]
    pagination_class = MerchantPagination


class MerchantSearchView(generics.ListAPIView):
    class MerchantSearchFilter(filters.SearchFilter):
        search_param = 'q'

    authentication_classes = [JWTAuthentication]
    queryset = Merchant.objects.all()
    serializer_class = MerchantSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [MerchantSearchFilter]
    search_fields = ['name', 'categories__name', 'categories__goods_list__name']


class CategoryView(views.APIView):
    def get(self, request, merchant_id=None):
        categories = GoodsCategory.objects.filter(merchant=merchant_id)
        serializer = GoodsCategorySerializer(categories, many=True)
        return Response(serializer.data)


class AddressViewSet(viewsets.ModelViewSet):
    authentication_classes = [JWTAuthentication]
    serializer_class = AddressSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        return self.request.user.addresses.all()

    def perform_create(self, serializer):
        is_default = serializer.validated_data.get('is_default')
        if is_default:
            self.request.user.addresses.update(is_default=False)
        serializer.save(user=self.request.user)

    def perform_update(self, serializer):
        is_default = serializer.validated_data.get('is_default')
        if is_default:
            self.request.user.addresses.update(is_default=False)
        serializer.save()

    # /address/default
    @action(['GET'], detail=False, url_path='default')
    def default_address(self, request):
        try:
            address = self.request.user.addresses.get(is_default=True)
        except:
            address = self.request.user.addresses.first()
        serializer = self.serializer_class(address)
        return Response(serializer.data)

